package com.tosee.dao.dbTosee.impl;

import java.sql.SQLException;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import com.tosee.dao.dbTosee.ISerieDao;
import com.tosee.dao.hibernate.impl.HibernateGenericDao;
import com.tosee.model.dbTosee.Serie;

@Repository
public class SerieDao extends HibernateGenericDao<Serie, Long> implements ISerieDao {

    /**
     * Constructeur du DAO.
     * 
     * @param sessionFactory {@link SessionFactory} Hibernate
     */
    @Autowired
    public SerieDao(SessionFactory sessionFactory) {
        super(Serie.class, sessionFactory);
    }

    @Override
    public Serie getSerieByCodeAllocine(final Integer _code) {
        Serie serie = null;
        if(_code != null) {
            serie = (Serie) getHibernateTemplate().execute(new HibernateCallback() {

                @Override
                public Object doInHibernate(Session _session) throws HibernateException, SQLException {

                    // Construction de la requete
                    StringBuilder requeteBuilder = new StringBuilder(200);
                    requeteBuilder.append("SELECT serie ");
                    requeteBuilder.append("FROM Serie serie ");
                    requeteBuilder.append("WHERE serie.codeAllocine = :code ");

                    // Exécution de la requete
                    Query requete = _session.createQuery(requeteBuilder.toString());
                    requete.setInteger("code", _code);

                    return (Serie) requete.uniqueResult();
                }
            });
        }
        return serie;
    }
}
